package org.melord.cap;

import java.io.InputStream;
import java.util.Properties;

public class HttpRequest {
	private String method;
	private String protocol;
	private String requestURI;
	private String host;
	private String referer;
	private String location;
	private Properties headers = new Properties();

	private Object body;
	private InputStream inputStream;

	public void addHeader(String name, String value) {
		if ("Host".equalsIgnoreCase(name)) {
			host = value;
		} else if ("Referer".equalsIgnoreCase(name)) {
			referer = value;
		} else if ("Location".equalsIgnoreCase(name)) {
			location = value;
		}
		headers.put(name, value);
	}

	/**
	 * Get method
	 * 
	 * @return the method
	 */
	public String getMethod() {
		return method;
	}

	/**
	 * Set the method
	 * 
	 * @param method
	 *            the method to set
	 */
	public void setMethod(String method) {
		this.method = method;
	}

	/**
	 * Get protocol
	 * 
	 * @return the protocol
	 */
	public String getProtocol() {
		return protocol;
	}

	/**
	 * Set the protocol
	 * 
	 * @param protocol
	 *            the protocol to set
	 */
	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getHost() {
		return host;
	}

	public String getRequestURI() {
		return requestURI;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setRequestURI(String requestURI) {
		this.requestURI = requestURI;
	}

	public void setBody(Object body) {
		this.body = body;
	}

	public Object getBody() {
		return body;
	}

	public String getContentType() {
		String ret = headers.getProperty("Content-Type");
		return ret;
	}

	public int getContentLength() {
		int len = -1;
		String ret = headers.getProperty("Content-Length");
		if (ret != null) {
			try {
				Integer.parseInt(ret);
			} catch (NumberFormatException e) {

			}
		}
		return len;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getReferer() {
		return referer;
	}

	public void setReferer(String referer) {
		this.referer = referer;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(method);
		sb.append(" ");
		sb.append(requestURI);
		sb.append(" ");
		sb.append(protocol);
		sb.append('\n');
		for (Object key : headers.keySet()) {
			sb.append(key);
			sb.append(": ");
			sb.append(headers.get(key));
			sb.append('\n');
		}
		if (body != null) {
			sb.append(body.toString());
		}
		return sb.toString();
	}

}
